import { Injectable,HttpException, HttpStatus  } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { LuckyInfo,Lucky } from '../entity';
import { Repository,EntityRepository } from 'typeorm';
import { AppError } from '../error/index';

@Injectable()
export class LuckService {
  constructor(

    @InjectRepository(LuckyInfo)
    private readonly luckInfoRepository: Repository<LuckyInfo>,

    @InjectRepository(Lucky)
    private readonly luckRepository: Repository<Lucky>
    ) { }
  
  async findOne(id: number): Promise<LuckyInfo> {
    const result = await this.luckInfoRepository.findOne({ id });
    if (result) {
      return result;
    }
    throw new AppError('未找到相关内容', 20);
  }

  async createDraw(luckId,body): Promise<Lucky>{
    const { userId } = body;
    const luckInfo = await this.luckRepository.findOne({ luckId });
    if(!luckInfo){throw new AppError('没有此活动', 20);}
    const res = await this.luckRepository.findOne({ luckId,userId });
    if (res) { throw new AppError('已参与活动', 20);}
    const result = await this.luckRepository.save(body);
    return result;
  }

  async updateLuck(luckId,body): Promise<any>{
    const { userId,type,isLucky } = body;
    const result = await this.luckRepository.findOne({ luckId, userId });
    if (!result) {
      throw new AppError('未参与活动', 20);
    }
    const res = { ...result, type,isLucky };
    const _result = await this.luckRepository.save(res);
    return result;
  }
}